package com.itheima.controller;

import com.itheima.pojo.BsUser;
import com.itheima.service.LoginService;
import com.itheima.util.LoginResult;
import com.itheima.util.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@RestController
@RequestMapping("/frame")
public class LoginController {
    @Autowired
    private LoginService loginService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;
    //用户登录
    @PostMapping("/login")
    public Token login(String username, String password){
//        String newpassword = DigestUtils.md5DigestAsHex(password.getBytes());
        BsUser bsUser = loginService.login(username,password);
        if(bsUser==null){
            return null;
        }
        //生成Token令牌
        String token = UUID.randomUUID()+"";
        loginService.savetoken(bsUser,token);
        return new Token(token);
    }
    //用户信息获取
    @PostMapping("/profile")
    public LoginResult profile(){
        String cookie = request.getHeader("Authorization");
        String[] split = cookie.split(" ");
        LoginResult loginResult = loginService.profile(split[1]);
        return loginResult;
    }
    //用户退出
    @PostMapping("/logout")
    public void logout(){
        String cookie = request.getHeader("Authorization");
        String[] split = cookie.split(" ");
        loginService.logout(split[1]);
    }
}
